package vincent.com.layouttest.service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import vincent.com.layouttest.IAIDLServiceInterface;
import vincent.com.layouttest.R;
import vincent.com.layouttest.entity.BroadcastImpl;
import vincent.com.layouttest.util.Const;
import vincent.com.layouttest.util.LogUtil;
import vincent.com.layouttest.util.PreferenceUtil;

/**
 * Created by chenzhengwen on 2015/12/8.
 */
public class AIDLServiceActivities extends AppCompatActivity {
    private int mVal = 0;
    public static final String FOREGROUND = "foreground";

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    mServiceReturn.setText(msg.arg1 + "");
                    break;
                case 2:
                    String myPrefVal = null;
                    try {
                        myPrefVal = mAIDLService.getMyPreferenceVal();
                    } catch (RemoteException e) {
                        System.err.println(e.getMessage());
                    }
                    if(myPrefVal != null && !"".equals(myPrefVal)){
                        mMyPrefValService.setText(mMyPrefValService.getText() + myPrefVal);
                    }
                    break;
                case 3:
                    //get preference instance with Context.MODE_PRIVATE flag
//                    String val = PreferenceUtil.getStringField(AIDLServiceActivities.this, Const.MY_PREFERENCE_FIELD);

                    //get preference instance with Context.MODE_MULTI_PROCESS flag
                    String val = PreferenceUtil.getStringField(AIDLServiceActivities.this, Const.MY_PREFERENCE_FIELD, Context.MODE_MULTI_PROCESS);
                    LogUtil.i(LogUtil.DEBUG_TAG, "AIDLServiceActivities get preference val=" + val);
                    mMyPrefValMain.setText(val);
                    mHandler.sendEmptyMessageDelayed(3, 500);
                    break;
                case 4:
                    try {

//                        String myVal = PreferenceUtil.getStringField(AIDLServiceActivities.this, Const.MY_PREFERENCE_FIELD);
                        String myVal = mAIDLService.getMyPreferenceVal();
                        if(TextUtils.isEmpty(myVal)){
                            mVal = 1;
                        }else{
                            mVal = Integer.parseInt(myVal) + 1;
                        }

                        LogUtil.i(LogUtil.DEBUG_TAG, "AIDLServiceActivities 4 myVal=" + myVal);
                        mMyPrefValMain.setText(myVal);
                        mAIDLService.setMyPreferenceVal("" + mVal);

                        sendEmptyMessageDelayed(4, 1000);
                    } catch (RemoteException e) {
                        System.err.println(e.getMessage());
                    }
                    break;
            }
        }
    };

    private boolean mBound = false;
    private IAIDLServiceInterface mAIDLService;

    private ServiceConnection mServiceConn = new ServiceConnection() {

        //service参数是Client端的代理Binder对象
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mAIDLService = IAIDLServiceInterface.Stub.asInterface(service);

            try{
                //获取后台 BroadcastImpl 实例并赋值给前台实例
                BroadcastImpl backgroundImpl = mAIDLService.getBroadcastImpl();
                BroadcastImpl.getInstance(FOREGROUND).setRemoteInstance(backgroundImpl);

                //将前台 BroadcastImpl 实例赋值给后台
                mAIDLService.setBroadcastImpl(BroadcastImpl.getInstance(FOREGROUND));

                mBound = true;
            }catch (RemoteException e){
                LogUtil.e("exception--->", e.getMessage());
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
            mAIDLService = null;
        }
    };

    private TextView mServiceReturn;
    private TextView mMyPrefValMain;
    private TextView mMyPrefValService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidl_service);
        mServiceReturn = (TextView)findViewById(R.id.service_return);
        mMyPrefValMain = (TextView)findViewById(R.id.my_pref_val_main_process);
        mMyPrefValService = (TextView)findViewById(R.id.my_pref_val_service_process);
        bindService(new Intent(this, AIDLService.class), mServiceConn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        bindService(new Intent(this, AIDLService.class), mServiceConn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if(mBound){
//            unbindService(mServiceConn);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mBound){
            unbindService(mServiceConn);
        }
    }

    public void randomInt(View v){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int result = mAIDLService.getRandomInt();
                    Message msg = Message.obtain(mHandler, 1, result, 0);
                    mHandler.sendMessage(msg);
                } catch (RemoteException e) {
                    System.err.println(e.getMessage());
                }
            }
        }).start();
    }

    //set preference in main process an get the value from another process
    public void getMyPrefVal(View v) {
        PreferenceUtil.setStringField(this, Const.MY_PREFERENCE_FIELD, "fill");
        mMyPrefValMain.setText(mMyPrefValMain.getText() + PreferenceUtil.getStringField(this, Const.MY_PREFERENCE_FIELD));

//        mHandler.sendEmptyMessageDelayed(2, 1000);
        mHandler.sendEmptyMessage(2);
    }

    //set preference value from another process
    public void setMyPrefVal(View v) {
        mHandler.sendEmptyMessage(4);
        v.setEnabled(false);
    }

    public void getAsycPrefVal(View v){
        mHandler.sendEmptyMessage(3);
    }

    public void interrupt(View v){
        try {
            mAIDLService.setMyPreferenceVal("1000");
        } catch (RemoteException e) {
            System.err.println(e.getMessage());
        }
    }

    public void aidlEmptyString(View v){
        try {
            mAIDLService.getEmptyString();
        } catch (RemoteException e) {
            System.err.println(e.getMessage());
        }
    }

    public void onForeFuck(View view){
        //前台进程调用
        BroadcastImpl.getInstance(FOREGROUND).fuck();
        //后台进程调用
        BroadcastImpl.getInstance(FOREGROUND)
                .getRemoteInstance()
                .fuck();
    }

    public void onBackFuck(View view){
        try{
            mAIDLService.callFuck();
        }catch (RemoteException e){
            LogUtil.e("exception--->", e.getMessage());
        }
    }
}
